﻿#pragma once
#include "snake.h"

void GotoXY1(HANDLE hOut1, int x, int y)  // 移动 
{
	COORD pos;
	pos.X = x;   //横坐标
	pos.Y = y;  //纵坐标
	SetConsoleCursorPosition(hOut1, pos);
}
HANDLE hOut1 = GetStdHandle(STD_OUTPUT_HANDLE);//定义显示器句柄变量

Snake::Snake(Wall& tempWall, Food& tempFood) :wall(tempWall), food(tempFood)
{
	pHead = NULL;
	isRool = false;
}

void Snake::initSnake()
{
	destroyPoint();

	//创建游戏开始时的蛇
	addPoint(5, 3);
	addPoint(5, 4);
	addPoint(5, 5);
}

void Snake::destroyPoint()
{
	//临时节点指向头节点 依次后移删除节点直到为空
	Point* pCur = pHead;

	while (pCur!=NULL)
	{
		pCur = pHead->next;
		delete pHead;
		pHead = pCur;
	}
}

void Snake::addPoint(int x,int y)
{
	//创建新节点
	Point* newPoint = new Point;

	newPoint->x = x;
	newPoint->y = y;

	newPoint->next = NULL;

	//如果原来头节点不为空,就改成身子
	if (pHead != NULL) {
		wall.setwall(pHead->x, pHead->y, '=');
		GotoXY1(hOut1, pHead->y * 2, pHead->x);
		cout << "=";
	}

	newPoint->next = pHead;

	//更新头节点
	pHead = newPoint;
	wall.setwall(pHead->x, pHead->y, '@');
	GotoXY1(hOut1, pHead->y * 2, pHead->x);
	cout << "@";
}

void Snake::delPoint()
{
	//两个以上的节点才去做删除操作
	if (pHead->next == NULL || pHead == NULL)
	{
		return;
	}

	Point* pCur = pHead->next;
	Point* pPer = pHead;

	while (pCur->next !=NULL)
	{
		pPer = pPer->next;
		pCur = pCur->next;
	}

	//删除尾节点
	wall.setwall(pCur->x, pCur->y, ' ');
	GotoXY1(hOut1, pCur->y * 2, pCur->x);
	cout << " ";
	delete pCur;
	pCur = NULL;
	pPer->next = NULL;
}

bool Snake::move(char key)
{
	int x = pHead->x;
	int y = pHead->y;

	switch (key)
	{
	case UP:
		x--;
		break;
	case DOWN:
		x++;
		break;
	case LEFT:
		y--;
		break;
	case RIGHT:
		y++;
		break;
	default:
		break;
	}

	Point* pCur = pHead->next;
	Point* pPer = pHead;

	while (pCur->next != NULL)
	{
		pPer = pPer->next;
		pCur = pCur->next;
	}

	if (pCur->x == x && pCur->y == y)
	{
		isRool = true;
	}
	else
	{
		//移动错误
		if (wall.getwall(x, y) == '*')
		{
			//死亡撞墙 多走一步
			addPoint(x, y);
			delPoint();
			system("cls");
			wall.showwall();

			cout << "得分为:" << getScore() << endl;
			cout << "GAEM OVER" << endl;
			return false;
		}
		if (wall.getwall(x, y) == '=')
		{
			addPoint(x, y);
			system("cls");
			wall.showwall();

			cout << "得分为:" << getScore() << endl;
			cout << "GAEM OVER" << endl;
			return false;
		}
	}

	//移动正确
	//判断是否吃到食物
	//吃到食物
	if (wall.getwall(x, y) == '#')
	{
		addPoint(x, y);
		food.setFood();
	}
	else 
	{
		//未吃到食物
		addPoint(x, y);
		delPoint();

		if (isRool)
		{
			wall.setwall(x, y, '@');
			GotoXY1(hOut1, y * 2, x);
			cout << "@";
		}
	}
	return true;
}

int Snake::getList()
{
	int size = 0;

	Point* temp = pHead;
	while (temp != NULL)
	{
		size++;
		temp = temp->next;
	}
	return size;
}

int Snake::getSleepTime()
{
	int size = getList();

	int sleepTime = 0;

	if (size < 5) {
		sleepTime = 300;
	}
	else if (size >= 5 && size < 10)
	{
		sleepTime = 200;
	}
	else if (size >= 10)
	{
		sleepTime = 100;
	}
	return sleepTime;
}

int Snake::getScore()
{
	int size = getList();

	return (size - 3) * 100;
}
